//
//  UserMainController.swift
//  FarmShare
//
//  Created by XingJian Li on 2018/3/15.
//  Copyright © 2018年 aykj. All rights reserved.
//

import Foundation
import Alamofire

class jsonModel: NSObject {
    var newsClassPic:String!
    var newsClassId:String!
    var newsClassName:String!
}

class MainIndex: UIViewController {
    
    var tableView: UITableView!
    
    var currentPage:Int? = 1
    var totalPage:Int? = 0
    var hotNewsArray = [investmentDynamicsModel]()
    
    
    var newsListArray = [investmentDynamicsModel]()
    
    var mainArray = [MainModel]()
    
    var nameArray : [String] = ["投资动态","投资环境","招商项目","信息公开","资料下载","区县版","联系我们","个人中心"]
    
    var ImageViewArray : [String] = ["touzi","huanjing","zhaoshang","xinxigongkai","xiazaiziliao","quxianban","lianxiwomen","gerenzhongxin"]
    
    
    var cellArray : [String] = ["江林集团新能源汽车昆明基地","省招生局与山东开发食品","江林集团新能源汽车昆明基地","江林集团新能源汽车昆明基地","江林集团新能源汽车昆明基地","江林集团新能源汽车昆明基地","江林集团新能源汽车昆明基地","江林集团新能源汽车昆明基地"]
    
    
    let netAdArray = ["http://pic27.nipic.com/20130329/890845_115317964000_2.jpg",
                      "http://pic1.nipic.com/2008-12-16/2008121622355688_2.jpg",
                      "http://pic29.nipic.com/20130601/12122227_123051482000_2.jpg",
                      "http://pic22.nipic.com/20120625/8534374_064230576000_2.jpg"]
    
    /// 例一：简单使用、默认分页控件
    lazy var cycleScrollView1: FWCycleScrollView = {
        
        let cycleScrollView = FWCycleScrollView.cycle(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.width/2))
        cycleScrollView.backgroundColor = UIColor.groupTableViewBackground
        cycleScrollView.imageUrlStrArray = netAdArray
        return cycleScrollView
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = bgGrayColor;
         navigationItem.title="首页"
        
         self.loadData()
//        self.edgesForExtendedLayout = UIRectEdge(rawValue: 0) // UIRectEdge(rawValue: 0) //导航栏下开始计算高度

        
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height-49), style: .plain )
        tableView.dataSource = self
        tableView.delegate = self

        tableView.backgroundColor = bgGrayColor

        self.view.addSubview(tableView)
        
        
        
        tableView.register(NSClassFromString("OneTableViewCell"), forCellReuseIdentifier: "OneTableViewCell")
        tableView.register(NSClassFromString("TwoTableViewCell"), forCellReuseIdentifier: "TwoTableViewCell")

        self.initHead()
    }
    
    func loadData() {
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/index/getNewsClass"
        let url = URL(string: urlString)!

        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
   

        Alamofire.request(request).responseJSON {
            (response) in
                print("-----\(response)")
            
            if response.result.isSuccess {
                let json = JSON(response.data!)
                
                let array  = json["resultData"].array;
                
                for dataDic in  array!
                {
                    let model =   MainModel()
                    
                    model.newsClassId = dataDic["newsClassId"].string
                    model.newsClassName = dataDic["newsClassName"].string
    
                    model.newsClassPic = dataDic["newsClassPic"].string
                    
                    
                    self.mainArray.append(model)
                                        
                }
 

        }
            

            //首页投资动态
            let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/index/investmentDynamics"
            let url = URL(string: urlString)!
            
            var request = URLRequest(url: url)
            request.httpMethod = HTTPMethod.post.rawValue
            
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            
            
         
            
            Alamofire.request(request).responseJSON {
                (response) in
                
                print("shouye====\(response)")
           
                
                if response.result.isSuccess {
                    let json = JSON(response.data!)
                    
                    let dataDic = json["resultData"]["hotNews"];
    
                        let model =   investmentDynamicsModel()

                        model.articlePic = dataDic["articlePic"].string
                        model.createtime = dataDic["createtime"].string
                        model.ids = dataDic["articleId"].intValue
                        model.title = dataDic["title"].string
                      

                        self.hotNewsArray.append(model)
                    
                    
                    

                    
                    let array1 = json["resultData"]["newsList"].array
                    
                    
        
                    for dataDic in  array1! {
      
                    let model1 =   investmentDynamicsModel()
                    
                    model1.articlePic = dataDic["articlePic"].string
                    model1.createtime = dataDic["createtime"].string
                    model1.ids = dataDic["articleId"].intValue
                    model1.title = dataDic["title"].string
                    
                    
                    self.newsListArray.append(model)
                        
                    print("hotNewsArray====\(self.hotNewsArray.count)")
                    print("newsListArray====\(self.newsListArray.count)")
                    
                }

                    
                    self.tableView.reloadData()
                }
                
                
            }
        }
        
        
        
        
    }

    
    func initHead(){
        let headV = UIView()
        headV.width = self.view.width
        headV.addSubview(cycleScrollView1)
        headV.backgroundColor = bgGrayColor
        let funciontView = UIView();
        headV.addSubview(funciontView)
        
        funciontView.backgroundColor = UIColor.white
        var temp:[UIView] = []
        let margin:CGFloat = 1
        
        
        for i in 0...7{
            let view = self.getFunctionButton(funciontView: funciontView, name: nameArray[i], image: ImageViewArray[i], index: i)
            view.tag = i
            temp.append(view)
        }
        _ = funciontView.sd_layout().leftSpaceToView(headV, 0)?.rightSpaceToView(headV, 0)?.topSpaceToView(cycleScrollView1, 0)
        funciontView.setupAutoWidthFlowItems(temp, withPerRowItemsCount: 4, verticalMargin: margin, horizontalMargin: margin, verticalEdgeInset: 5, horizontalEdgeInset: 5)
        
        headV.setupAutoHeight(withBottomView: funciontView, bottomMargin: 10)
        headV.updateLayout()
        headV.layoutSubviews()
        self.tableView.tableHeaderView = headV
    }
    private func getFunctionButton(funciontView:UIView, name:String,image:String,index:Int)-> UIView {
        let view = UIView();
        view.backgroundColor = UIColor.white;
        funciontView.addSubview(view)
        _ = view.sd_layout().autoHeightRatio(0.7)
        
        let image = UIImageView.init(image: UIImage.init(named: image))
        view.addSubview(image)
        _ = image.sd_layout().centerXEqualToView(view)?.topSpaceToView(view,5)?.widthIs(30)?.heightIs(30)
        
        let title = UILabel()
        title.textColor = color_f_title
        title.text = name
        title.font = UIFont.systemFont(ofSize: 12)
        view.addSubview(title)
        _ = title.sd_layout().bottomSpaceToView(view,5)?.centerXEqualToView(view)?.heightIs(15)?.autoWidthRatio(0)
        title.setSingleLineAutoResizeWithMaxWidth(100)
        
        view.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(openMerchantListVC(tap:))))
        return view
    }
    
    @objc func openMerchantListVC(tap:UITapGestureRecognizer){
        
        
        print(tap.view?.tag as Any)
        if tap.view?.tag==0 {
            print("投资")
            
            let model0 = self.mainArray[0]
            
            //实例化一个将要跳转的viewController
            let DynamicVc = DynamicViewController()
            //跳转
            DynamicVc.numString = model0.newsClassId
            self.navigationController?.pushViewController(DynamicVc , animated: true)
            
        }else if tap.view?.tag == 1{
            print("环境")
            
            let  model1 = self.mainArray[1]
            //实例化一个将要跳转的viewController
            let EnvironmentVc = EnvironmentViewController()
            
            EnvironmentVc.numstring = model1.newsClassId
            //跳转
            self.navigationController?.pushViewController(EnvironmentVc , animated: true)
            
            
        }else if tap.view?.tag == 2{
            print("招商")
             let  model2 = self.mainArray[2]
            //实例化一个将要跳转的viewController
            let ProjectVc = ProjectViewController()
            
            ProjectVc.numstring = model2.newsClassId
            //跳转
            self.navigationController?.pushViewController(ProjectVc , animated: true)
            
        }else if tap.view?.tag == 3{
            print("信息")
            
            
            let  model3 = self.mainArray[3]
            //实例化一个将要跳转的viewController
            let InformationVc = InformationViewController()
            
            InformationVc.numstring = model3.newsClassId
            //跳转
            self.navigationController?.pushViewController(InformationVc , animated: true)
            
          
        }else if tap.view?.tag == 4{
            
            print("资料")
          
            let  model4 = self.mainArray[4]
            //实例化一个将要跳转的viewController
            let DataVc = DataViewController()
            //跳转
            DataVc.numstring = model4.newsClassId
            self.navigationController?.pushViewController(DataVc , animated: true)
            
            
        }else if tap.view?.tag == 5{
            print("区县")
            let  model5 = self.mainArray[5]
            let  CityVc = CityViewController()
            CityVc.numstring = model5.newsClassId
            self.navigationController?.pushViewController(CityVc , animated: true)
           
        }else if tap.view?.tag == 6{
            
            print("联系")
    
            //实例化一个将要跳转的viewController
            let ContactVc = ContactViewController()
            //跳转
            self.navigationController?.pushViewController(ContactVc , animated: true)
        }else {
            print("个人")
            self.tabBarController?.selectedIndex = 2
        }
    }
    
}
extension MainIndex: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            return self.hotNewsArray.count
        }else{
            return self.newsListArray.count
        }
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            return 240
        }else{
            return 40
        }
        
    }
    

    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        if indexPath.section == 0{
             let cellModel:investmentDynamicsModel = self.hotNewsArray[indexPath.row]
            
              print("222222===========\(cellModel.ids!)")
            let cell = OneTableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "OneTableViewCell")

            cell.BgImage.sd_setImage(with: NSURL.init(string: "http://pic27.nipic.com/20130329/890845_115317964000_2.jpg")! as URL, placeholderImage: UIImage.init(named: "bannerhomeOne"), options: [], progress: nil, completed:nil)

            cell.nameLabel.text = cellModel.title
             cell.selectionStyle = UITableViewCellSelectionStyle.none
            return cell
        }else{
            let cellModel:investmentDynamicsModel = self.newsListArray[indexPath.row]
            
            let cell = TwoTableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "TwoTableViewCell")
             cell.selectionStyle = UITableViewCellSelectionStyle.none
            cell.nameLabels.text = cellModel.title
            return cell
        }
        
        
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if indexPath.section == 0{
            let cellModel:investmentDynamicsModel = self.hotNewsArray[indexPath.row]
            
            let WebVC =  WebViewController()
            
            WebVC.numInteger = "\(cellModel.ids!)"
            self.navigationController?.pushViewController(WebVC , animated: true)
    
        }else{
            let cellModel:investmentDynamicsModel = self.newsListArray[indexPath.row]
            
            let WebVC =  WebViewController()
            WebVC.numInteger = "\(cellModel.ids!)"
            self.navigationController?.pushViewController(WebVC , animated: true)
       
        }
    }
    
}
